A function is called Higher Order Function if it contains other
functions as a parameter or returns a function as an output i.e, the
functions that operate with another functions are known as Higher order
Functions. It is worth knowing that higher order function is applicable
for functions and methods as well that takes functions as parameter or
returns a function as a result.
The map function is a classic example of a higher order function.
object demo
{
def doubleValue = (x: Int) => x * x
def main(args:Array[String])
{
val list = List(1,2,3)
val doubledList = list.map(x => doubleValue(x))
print(doubledList)
}
Create your own Higher order Function
object demo
{
def addition(f: (Int, Int) => Int,a: Int, b:Int): Int = f(a,b)
val squareSum = (x: Int, y: Int) => (x*x + y*y)
def main(args:Array[String])
{
val squaredSum = addition(squareSum, 1,2)
print(squaredSum)
}
}
object demo
{
def main(args: Array[String])
{
val names = Set("Sunil","Akhil","Rakhi")
def captainDesignation = (y: String) => "Captain " + y
val result = names.map(y => captainDesignation(y))
println("Multiplied List is: " + result)
}
}
{
def main(args: Array[String])
{
val names = Set("Sunil","Akhil","Rakhi")
def captainDesignation = (y: String) => "Captain " + y
val result = names.map(y => captainDesignation(y))
println("Multiplied List is: " + result)
}
}
OutPut:-
Multiplied List is: Set(Captain Sunil, Captain Akhil, Captain Rakhi)
Find the Square root of the Function
object demo
{
def main(args :Array[String])
{
val lst=List(1,2,3,4,5,6)
def dbl=(x:Int)=> x*x
val result=lst.map(x=> dbl(x))
println("Multiplied List is: " + result)
}
}
OutPut:-
Multiplied List is: List(1, 4, 9, 16, 25, 36)
Find the Square root of the Function
object demo
{
def main(args:Array[String]){
def addition(f: (Int, Int) => Int,a: Int, b:Int): Int = f(a,b)
val squareSum = (x: Int, y: Int) => (x*x + y*y)
val cubeSum = (x: Int, y: Int) => (x*x*x + y*y*y)
val intSum = (x: Int, y: Int) => (x + y)
val squaredSum = addition(squareSum, 1, 2)
val cubedSum = addition(cubeSum, 1, 2)
val normalSum = addition(intSum, 1, 2)
println (squaredSum)
println (cubedSum)
println (normalSum)
}
}
No comments:
Post a Comment